<?php

namespace App\Service\Kms\SelfCheck;

use App\Library\Rms\RmsUserApi;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Cruise\CruiseOrderProcessModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Models\Kms\User\KmsUser;
use App\Models\Shop\ShopModel;
use App\Service\BaseService;
use App\Service\Cruise\Mission\CheckInputService;
use App\Service\OpenShop\User\RmsUserService;
use App\Support\CustomForm\AttributeCruiseSupport;

class SelfCheckReportService extends BaseService
{
    public static function detail(int $id, int $userId, string $platform = 'merchant')
    {
        $cruiseOrder = CruiseOrderModel::query()->find($id);
        if (!$cruiseOrder || $cruiseOrder->type != CruiseTemplateModel::TYPE_8) {
            BaseService::throwErr('不存在的自检报告');
        }

        $detail = $cruiseOrder->checkTaskDetailRel;
        if (!$detail) {
            BaseService::throwErr('不存在的巡检报告~');
        }

        $shop     = ShopModel::query()->find($cruiseOrder->shopId);
        $shopName = $shop ? ($shop->shopCode . $shop->name) : '';

        // inputs
        $inputObj = (new CheckInputService($id, $userId));
        $inputs = $inputObj->getInputObjectFill()['lists'] ?? [];

        // submit
        $submit = CruiseOrderProcessModel::query()
                                         ->where("cruiseOrderId", $id)
                                         ->where("step", CruiseOrderProcessModel::PROCESS_SUBMITTED)
                                         ->orderByDesc("id")
                                         ->first();
        if ($submit) {
            $submitUserId = $submit->createdByUid;
            $submitUserName = RmsUserService::getRmsUserInfoByUserIds([$submitUserId])['data'][0]['username'] ?? '';

            if (in_array($cruiseOrder->shopId, (new RmsUserApi())->getShopIdsByUserManager($submitUserId)['data']['shopIds'] ?? [])) {
                $role = '店长';
            } else {
                $role = '店员';
            }

        } else {
            $submitUserId = 0;
            $submitUserName = '-';
            $role = '-';
        }

        // audit
        $audit = CruiseOrderProcessModel::query()
                                        ->where("cruiseOrderId", $id)
                                        ->where("step", CruiseOrderProcessModel::PROCESS_SELF_REVIEWED)
                                        ->orderByDesc("id")
                                        ->first();
        if ($audit) {
            $auditUserId = $audit->createdByUid;
            $auditUserName = KmsUser::getUserInfo([$auditUserId])[$auditUserId] ?? '-';
            $auditTime = date('Y-m-d H:i:s', $audit->createdAt->timestamp);

            $successNum = 0;
            $failNum = 0;

            foreach ($inputs as $input) {
                foreach ($input['projects'] as $i) {
                    if (in_array($i['inputType'], AttributeCruiseSupport::CRUISE_CHECK_MODULE)) {

                        if ($i['value'] == AttributeCruiseSupport::CRUISE_CHECK_OK) {
                            $successNum++;
                        } elseif ($i['value'] == AttributeCruiseSupport::CRUISE_CHECK_FAIL) {
                            $failNum++;
                        }
                    }
                }
            }

            $totalNum = $successNum + $failNum;

            $successRate = $totalNum ? bcdiv($successNum * 100, $totalNum, 2) . '%' : '-';


        } else {
            $auditUserId = 0;
            $auditUserName = '-';
            $auditTime = '-';
            $failNum = '-';
            $successRate = '-';
        }

        // statusText
        $statusText = CruiseOrderModel::CRUISE_STATUS_MAPPING[$cruiseOrder->status] ?? '';
        if ($platform == 'merchant') {
            if ($cruiseOrder->status == CruiseOrderModel::STATUS_NOT_REVIEW) {
                $statusText = '已提交';
            }
        }
        if ($cruiseOrder->status == CruiseOrderModel::STATUS_NOT_SUBMIT) {
            $statusText = '待完成';
        }

        // 审核权限
        if ($platform == 'merchant') {
            $enableAudit = false;
        } else {

            // 自检审核人
            // 督导、城市经理、省总、战区总
            $enableAudit = in_array($userId, $inputObj->getCurrentHandlerInfo(CruiseOrderModel::STATUS_NOT_REVIEW)['userIds'] ?? []);
        }

        // 督导能审核的情况下，需要特殊处理value值。督导没操作过的项，value给null
        if ($enableAudit) {
            foreach ($inputs as &$input) {
                foreach ($input['projects'] as &$project) {

                    if (in_array($project['inputType'], AttributeCruiseSupport::CRUISE_CHECK_MODULE) && $project['value'] != AttributeCruiseSupport::CRUISE_CHECK_SKIP) {

                        if (!isset($project['customAttributes']['auditValue']['instructions'])) {
                            $project['value'] = null;
                        }
                    }
                }
            }
        }

        return [
            'task'        => [
                'name'            => $detail->taskName . "（". date('m月d号', $detail->createdAt->timestamp). "）",
                'shopName'        => $shopName,
                'sysTemplateText' => CruiseTemplateModel::SYS_TEMPLATE_TEXT[$detail->sysTemplate] ?? '',
                'startDateTime'   => $detail->firstSaveTime ? date('Y-m-d H:i:s', $detail->firstSaveTime) : '-',
                'endDateTime'     => $detail->submitTime ? date('Y-m-d H:i:s', $detail->submitTime) : '-',
                'executeDuration' => ($detail->submitTime && $detail->firstSaveTime) ? ($detail->submitTime - $detail->firstSaveTime) : '-',
                'taskNum'         => $detail->totalNum,
                'iconStatus'      => $cruiseOrder->status,
            ],
            'submit'      => [
                'userId'   => $submitUserId,
                'userName' => $submitUserName,
                'role'     => $role,
            ],
            'audit'       => [
//                'status'      => $cruiseOrder->status,
                'statusText' => $statusText,
                'successRate' => $successRate,
                'failNum'     => $failNum,
                'userId'      => $auditUserId,
                'userName'    => $auditUserName,
                'auditTime'   => $auditTime,
            ],
            'enableAudit' => $enableAudit,
            'inputs'      => $inputs,
        ];
    }
}
